package com.zhouyou.http.model.utils;

import com.zhouyou.http.utils.TextUtils;
import ohos.app.Context;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;

import java.io.*;

public class FileUtils {

    public static String getFileName(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return filePath;
        }

        int filePosi = filePath.lastIndexOf(File.separator);
        return (filePosi == -1) ? filePath : filePath.substring(filePosi + 1);
    }


    /**
     * 获取本地存储文件
     * @param context
     * @param fileName
     * @return
     */
    public  static  File getDistributedDir(Context context,String fileName){
        File distDir = context.getDistributedDir();
        return new  File( context.getExternalCacheDir() + File.separator + fileName) ;
    }

    public  static  InputStream getRawFile(Context context,String fileName) throws IOException {
        ResourceManager resManager = context.getResourceManager();
        RawFileEntry rawFileEntry = resManager.getRawFileEntry("resources/rawfile/"+fileName);
       return  rawFileEntry.openRawFile();
    }

    /*
    * 获取Asset内的文件夹
    * @param fileName 必须是完整文件名（文件名+格式）
    */
    public static void getFileFromRawfile(Context context, String fileName) {
        try {
            ResourceManager resManager = context.getResourceManager();
            RawFileEntry rawFileEntry = resManager.getRawFileEntry("resources/rawfile/"+fileName);
            Resource resource =rawFileEntry.openRawFile();
            String filePath = context.getExternalCacheDir()+ File.separator+fileName;
            saveFileDistributedDir(resource,filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public  static  String  getDistDir(Context context){
        return  context.getExternalCacheDir()+File.separator;
    }

   public static void  saveFileDistributedDir( Resource resource,String filePath ){
       inputStreamToFile(resource,new File(filePath));
   }


    /**
     * InputStream转 File类型
     * @param ins
     * @param file
     */
    public static void  inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }
}
